import { FC, useCallback, useEffect, useMemo, useState } from 'react';
import { Badge, DatePicker, Input, Select } from 'antd';
import { isArray, isNil } from 'lodash';
import { observer } from 'mobx-react';

import RbProTable, { RbProTableStore } from '@components/RbProTable';
import { Content } from '@components/Page';
import {
  COMMON_REQUIRE_RULE,
  COMMON_SELECT_FIELDSNAMES,
  COMPLETELY_FILL_STYLE
} from '@utils/config';
import { Status } from '@enumTypes/enumTypes';
import { generateCommonDeleteModal, generateCommonSelect } from '@utils/renderer';
import { getDictionaryListApi } from '@services/service';
import Button from '@components/Button';
import request from '@utils/request';
import notification from '@utils/notification';
import { TableAlignType } from '@enumTypes/table';

const store = new RbProTableStore();

const JobInfo: FC = () => {
  // 加载状态
  const { query } = store;

  // 字典数据
  const [statusList, setStatusList] = useState<any[]>([]);
  const [jobExecutorTypeList, setJobExecutorTypeList] = useState<any[]>([]);
  const [jobMisfirePolicyList, setJobMisfirePolicyList] = useState<any[]>([]);
  const [yesNoList, setYesNoListList] = useState<any[]>([]);

  /** 查询设置字典数据 */
  const handleQueryDictionaryList = useCallback(() => {
    getDictionaryListApi([
      'RB_STATUS',
      'RB_JOB_EXECUTOR_TYPE',
      'RB_JOB_MISFIR_POLICY',
      'RB_YES_NO'
    ]).then((res: any) => {
      if (isArray(res)) {
        const [statusList, jobExecutorTypeList, jobMisfirePolicyList, yesNoList = []] = res || [];
        setStatusList(statusList);
        setJobExecutorTypeList(jobExecutorTypeList);
        setJobMisfirePolicyList(jobMisfirePolicyList);
        setYesNoListList(yesNoList);
      }
    });
  }, []);

  // 暂停任务
  const handlePauseJob = useCallback(() => {
    if (!store.selectedKeys.length) return;

    generateCommonDeleteModal({
      title: '是否停止任务？',
      onOk() {
        store.loading = true;
        request({
          url: '/job/pause/' + store.selectedKeys[0],
          method: 'POST'
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              await store.query();
            }
          })
          .finally(() => {
            store.loading = false;
          });
      }
    });
  }, []);

  // 启动任务
  const handleResumeJob = useCallback(() => {
    if (!store.selectedKeys.length) return;

    generateCommonDeleteModal({
      title: '是否启动任务？',
      onOk() {
        store.loading = true;
        request({
          url: '/job/resume/' + store.selectedKeys[0],
          method: 'POST'
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              query();
            }
          })
          .finally(() => {
            store.loading = false;
          });
      }
    });
  }, []);

  useEffect(() => {
    handleQueryDictionaryList();
  }, []);

  // 查询条配置列表
  const queryFromItems = useMemo(
    () => [
      {
        name: 'jobName',
        label: '任务名称',
        children: <Input />
      },
      // {
      //   name: 'jobGroup',
      //   label: '任务分组',
      //   children: <Input/>
      // },
      {
        name: 'executorType',
        label: '任务类型',
        children: generateCommonSelect(jobExecutorTypeList)
      },
      {
        name: 'status',
        label: '状态',
        children: generateCommonSelect(statusList)
      },
      {
        name: 'createTime',
        label: '创建日期',
        children: <DatePicker.RangePicker />
      }
    ],
    [jobExecutorTypeList, statusList]
  );

  // 表格列配置
  const columns = useMemo(
    () => [
      {
        title: '任务名称',
        dataIndex: 'jobName',
        align: TableAlignType.center,
        width: 140
      },
      // {
      //   title: '任务分组',
      //   dataIndex: 'jobGroup',
      //   align: TableAlignType.center,
      //   width: 120
      // },
      {
        title: '任务类型',
        dataIndex: 'executorType',
        align: TableAlignType.center,
        render: (value: any) => {
          return (
            !isNil(value) && <>{value === 1 ? '简单模式' : value === 2 ? 'Corn表达式模式' : ''}</>
          );
        },
        width: 120
      },
      {
        title: '表达式',
        dataIndex: 'cronExpression',
        align: TableAlignType.center,
        width: 120
      },
      {
        title: '任务执行方法',
        dataIndex: 'executorHandler',
        align: TableAlignType.center,
        width: 250
      },
      {
        title: '任务参数',
        dataIndex: 'executorParams',
        align: TableAlignType.center,
        width: 250
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: TableAlignType.center,
        render: (value: any) => {
          return (
            !isNil(value) && (
              <>
                <Badge status={Status.enable === value ? 'success' : 'error'} />
                {value === 1 ? '运行中' : value === 0 ? '停止' : ''}
              </>
            )
          );
        },
        width: 120
      },
      {
        title: '备注',
        dataIndex: 'remark',
        ellipsis: true,
        width: 280
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        align: TableAlignType.center,
        sorter: true,
        width: 180
      }
    ],
    [jobExecutorTypeList]
  );

  // 新增表单配置
  const addFormItems = useMemo(
    () => [
      {
        name: 'jobName',
        label: '任务名称',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'jobGroup',
        label: '任务分组',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={[{ value: 'default', option: '默认分组' }]}
          />
        )
      },
      {
        name: 'executorType',
        label: '任务类型',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={jobExecutorTypeList}
          />
        )
      },
      {
        name: 'cronExpression',
        label: '表达式',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'executorHandler',
        label: '任务执行方法',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'executorParams',
        label: '任务参数',
        children: <Input />
      },
      {
        name: 'misfirePolicy',
        label: '计划执行错误策略',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={jobMisfirePolicyList}
          />
        )
      },
      {
        name: 'concurrent',
        label: '是否并发执行',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={yesNoList}
          />
        )
      },
      {
        name: 'remark',
        label: '备注',
        children: <Input.TextArea />
      }
    ],
    [jobExecutorTypeList, jobMisfirePolicyList, yesNoList]
  );

  // 编辑表单配置
  const updateFormItems = useMemo(
    () => [
      {
        name: 'jobName',
        label: '任务名称',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input disabled />
      },
      {
        name: 'jobGroup',
        label: '任务分组',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={[{ value: 'default', option: '默认分组' }]}
            disabled
          />
        )
      },
      {
        name: 'executorType',
        label: '任务类型',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={jobExecutorTypeList}
          />
        )
      },
      {
        name: 'cronExpression',
        label: '表达式',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'executorHandler',
        label: '任务执行类',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'executorParams',
        label: '任务参数',
        children: <Input />
      },
      {
        name: 'misfirePolicy',
        label: '计划执行错误策略',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={jobMisfirePolicyList}
          />
        )
      },
      {
        name: 'concurrent',
        label: '是否并发执行',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={yesNoList}
          />
        )
      },
      {
        name: 'remark',
        label: '备注',
        children: <Input.TextArea />
      }
    ],
    [jobExecutorTypeList, jobMisfirePolicyList, yesNoList]
  );

  return (
    <Content>
      <RbProTable
        rowKey="id"
        store={store}
        columns={columns}
        sticky
        selectionType
        actionUrl="/job"
        queryConfig={{
          queryFromItems,
          queryFormat: true
        }}
        addConfig={{
          addFormItems,
          addInitialValues: { jobGroup: 'default', concurrent: 0 }
        }}
        updateConfig={{ updateFormItems }}
        toolBarRender={() => [
          'add',
          'update',
          'delete',
          <Button
            key="pauseJob"
            type="primary"
            disabled={store.selected.length !== 1}
            onClick={() => handlePauseJob()}
          >
            停止任务
          </Button>,
          <Button
            key="resumeJob"
            type="primary"
            disabled={store.selected.length !== 1}
            onClick={() => handleResumeJob()}
          >
            启动任务
          </Button>
        ]}
      />
    </Content>
  );
};

export default observer(JobInfo);
